package cn.edu.hstc.wm.adapter;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import cn.edu.hstc.wm.service.AppConfigService;
import cn.edu.hstc.wm.ui.MainActivity;
import cn.edu.hstc.wm.utils.IntentUtil;

import cn.edu.hstc.wm.AppConfigs;
import cn.edu.hstc.wm.Constants;
import cn.edu.hstc.wm.R;

/**
 * @author act262 @ 2014-3-1 GuideViewPagerAdapter ViewPager适配器
 */

public class GuidePagerAdapter extends PagerAdapter {
	private static final String TAG = "ViewPagerAdapter";

	// 放入该ViewPager的View对象
	private List<View> mViews;

	// 当前的上下文
	private Activity mActivity;

	public GuidePagerAdapter(List<View> views, Activity activity) {
		this.mViews = views;
		this.mActivity = activity;
	}

	@Override
	public void destroyItem(View arg0, int arg1, Object arg2) {
		((ViewPager) arg0).removeView(mViews.get(arg1));
	}

	@Override
	public void finishUpdate(View arg0) {
	}

	@Override
	public int getCount() {
		if (mViews != null) {
			return mViews.size();
		}
		return 0;
	}

	// 初始化每个View
	@Override
	public Object instantiateItem(View arg0, int arg1) {
		((ViewPager) arg0).addView(mViews.get(arg1), 0);
		if (arg1 == mViews.size() - 1) { // 到最后一个

			ImageView goHomeIB = (ImageView) arg0.findViewById(R.id.iv_start_go_main);

			final CheckBox checkBox = (CheckBox) arg0.findViewById(R.id.checkBox1);

			goHomeIB.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					setGuided(checkBox.isChecked()); // 设置标记
					goHome();
				}
			});
		}
		return mViews.get(arg1);
	}

	// 跳转到主界面
	private void goHome() {
		switch (mActivity.getIntent().getIntExtra(Constants.START_GUIDE_PAGE_TYPE, 0)) {
		case Constants.START_GUIDE_PAGE_TYPE_FIRST_IN:
			IntentUtil.startActivity(mActivity, MainActivity.class);
			mActivity.finish();
			break;

		case Constants.START_GUIDE_PAGE_TYPE_SETTING:
			mActivity.finish();
			break;

		default:
			break;
		}
	}

	/**
	 * @param flag
	 *            是否勾选了'不再提示'
	 */
	private void setGuided(boolean flag) {
		AppConfigService.putBoolVal2Conf(mActivity, Constants.IS_FIRST_IN, !flag);
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return (arg0 == arg1);
	}

	@Override
	public void restoreState(Parcelable arg0, ClassLoader arg1) {
	}

	@Override
	public Parcelable saveState() {
		return null;
	}

	@Override
	public void startUpdate(View arg0) {
	}

}